# Tal网络模块
import json
import socket
import time
import threading

import src.util as util
from src.tal import Tal


class Server:
    def __init__(self):
        self.tal = Tal()

    def run_server(self, server, sock):
        # try:
        while 1:
            # 这个数字必须他妈大点啊 不然妈的东西都收不到
            data = sock.recv(20000).decode()
            if data == "exit" or not data:
                break
            # 统一处理请求
            print("\n\n\n收到请求,time->", util.getCurrentTimeFormat())
            res = self.tal.parse_operator(data)
            print("引擎处理结果为 ",res)
            sock.send(json.dumps(res).encode())

        sock.close()
        # except Exception as e:
        #     print("引擎出现问题，关闭socket连接,error->",e)
        #     sock.close()

    # 跑服务器
    def run(self, port):
        ip = "127.0.0.1"
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind((ip, int(port)))
        server.listen(5)
        print("引擎运行在{}:{}".format(ip, port))

        while 1:
            sock, addr = server.accept()
            t = threading.Thread(target=self.run_server, args=(server, sock))
            t.start()
